package com.neu.servlet.wty.demo.demo2;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.neu.service.wty.MgrService;
import com.neu.service.wty.UserService;
import org.json.JSONException;
import org.json.JSONObject;

import com.neu.servlet.wty.demo.sdk.GeetestLib;


/**
 * 使用post方式，返回验证结果, request表单中必须包含challenge, validate, seccode
 */

public class VerifyLoginServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(), 
				GeetestConfig.isnewfailback());

		HttpSession session=request.getSession();
		String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
		String validate = request.getParameter(GeetestLib.fn_geetest_validate);
		String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
		String auto_login=request.getParameter("auto_login");
		String u_tel =request.getParameter("u_tel");
		String u_pwd =request.getParameter("password");
		//从session中获取gt-server状态
		int gt_server_status_code = (Integer) session.getAttribute(gtSdk.gtServerStatusSessionKey);

		//从session中获取userid
		String userid = (String)session.getAttribute("userid");

		//得到用户名密码以及是否记住
		System.out.println("得到用户名密码以及是否记住密码");
		System.out.println("u_tel:"+u_tel);
		System.out.println("u_pwd:"+u_pwd);
		System.out.println("是否记住?   "+auto_login);
		//自定义参数,可选择添加
		HashMap<String, String> param = new HashMap<String, String>(); 
		param.put("user_id", userid); //网站用户id
		param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
		param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP
		
		int gtResult = 0;

		if (gt_server_status_code == 1) {
			//gt-server正常，向gt-server进行二次验证
				
			gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
			System.out.println(gtResult);
		} else {
			// gt-server非正常情况下，进行failback模式验证
				
			System.out.println("failback:use your own server captcha validate");
			gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
			System.out.println(gtResult);
		}
		Map<String,Object> mgr =null;
		Map<String,Object> user = null;
				//检测是否为管理员
		String check=u_tel.substring(0,3);
		if (check.equals("mgr")){
			//		查询管理员表
			MgrService mgrService = new MgrService();
			String m_no=u_tel;
			mgr = mgrService.checkLogin(m_no,u_pwd);
		}else {
			//		查询用户表
			UserService userService = new UserService();
			user = userService.checkLogin(u_tel,u_pwd);

		}

		//1为成功0为失败 2为管理员
		if (mgr==null&&user==null){
			gtResult=0;
			//验证失败
		}
		else if (mgr==null){
			gtResult=1;
		}else {
			gtResult=2;
        }


        //名为user的session 存放已登录的用户的信息 否则为null
        session.setAttribute("user",user);
        System.out.println("用户信息为"+user);
//		System.out.println("id:"+user.get("U_ID"));
        //名为mgr的session  存放已登录的管理员信息 否则为null
        session.setAttribute("mgr",mgr);
        System.out.println("管理员信息为"+mgr);


        if (auto_login!=null&&auto_login.equals("true")){
            Cookie c=new Cookie("auto_login",u_tel+":"+u_pwd);
            c.setMaxAge(1*7*24*60*60);
            c.setPath("/");
            response.addCookie(c);
            System.out.println("cookie已添加");
        }


		if (gtResult == 1) {
			// 普通用户验证成功
			PrintWriter out = response.getWriter();
			JSONObject data = new JSONObject();
			try {
				data.put("status", "success");
				data.put("version", gtSdk.getVersionInfo());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			out.println(data.toString());
//			System.out.println(data.toString());

//            System.out.println("准备跳转");
//            request.getRequestDispatcher("mian.jap").forward(request,response);
		}
		else if (gtResult==2){
			// 管理员验证成功
			PrintWriter out = response.getWriter();
			JSONObject data = new JSONObject();
			try {
				data.put("status", "mgr");
				data.put("version", gtSdk.getVersionInfo());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			out.println(data.toString());
		}
		else {
			// 验证失败
			JSONObject data = new JSONObject();
			try {
				data.put("status", "fail");
				data.put("version", gtSdk.getVersionInfo());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			PrintWriter out = response.getWriter();
			out.println(data.toString());
		}

	}

}
